package com.wuwangfu.transfor;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @Author jcshen
 * @Date 2023-02-22
 * @PackageName:com.wuwangfu.transfor
 * @ClassName: MinTransf
 * @Description:
 * @Version 1.0.0
 */
public class MinTransf {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        /**
         * hadoop,1
         * spark,2
         * hadoop,3
         * spark,5
         */
        DataStreamSource<String> line = env.socketTextStream("localhost", 8888);
        SingleOutputStreamOperator<Tuple2<String, Integer>> maped = line.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                String[] fields = value.split(",");
                return Tuple2.of(fields[0], Integer.valueOf(fields[1]));
            }
        });

        KeyedStream<Tuple2<String, Integer>, String> keyed = maped.keyBy(w -> w.f0);
        /**
         * minBy
         *  true 返回最前最小
         *  false 返回最后最小
         *  返回该行所有数据
         * min
         *  返回结果值和参与比较的字段
         *
         */
        keyed.minBy(1,true)
                        .print();


        env.execute();
    }
}
